package com.sloth.controller;

import com.sloth.mapper.MyorderMapper;
import com.sloth.mapper.ProductMapper;
import com.sloth.pojo.Address;
import com.sloth.pojo.Customer;
import com.sloth.pojo.Myorder;
import com.sloth.pojo.Product;
import com.sloth.service.AddressService;
import com.sloth.service.MyOrderService;
import com.sloth.service.PlaceAnOrderService;
import com.sloth.service.ProductService;
import com.sloth.util.ServerResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * @author lai
 * @time 2021/10/8 8:52
 */
// 用于下单页面的信息渲染
@Controller
public class PlaceAnOrderController {

    @Autowired
    private PlaceAnOrderService placeAnOrderService;

    @Autowired
    private ProductService productService;

    @Autowired
    private MyOrderService myOrderService;

    @Autowired
    private AddressService addressService;

    // 下单页面所需要的所有数据
    @PostMapping("order/place_an_order")
    @ResponseBody
    public String placeAnOrder(Customer customer , @RequestParam Map<String, String> productIdAndCount){

        // 1. 判断登录
        if (customer==null){
            return null;
        }

        // 已经登录的用户id
        Integer customerId = 0 ;

        // 创建一个可变的字符串来接收 商品id 对应的 数量
        StringBuilder builder = new StringBuilder();

        Iterator<Map.Entry<String, String>> iterator1 = productIdAndCount.entrySet().iterator();
        while (iterator1.hasNext()){
            Map.Entry<String, String> next = iterator1.next();
            String key = next.getKey();
            String value = next.getValue();
            builder.append("key" + key +"-" + value + "q");
        }

        customerId = customer.getCustId();

        /*while (attributeNames.hasMoreElements()){
            String s = attributeNames.nextElement().toString();
            System.out.println("ssss=========" + s);
            Customer customer = (Customer)session.getAttribute(s);
            customerId = customer.getCustId();
        }*/

        // 遍历从前台接收到的数据，里面包含订单的总价格、收货地址id、订单中的商品id及其对应的商品数量
        Iterator<Map.Entry<String, String>> iterator = productIdAndCount.entrySet().iterator();
//        Iterator<Map.Entry<String, String>> iterator = shopAndCount.entrySet().iterator();

        // 新创建一个 Map 集合，用于接收从前端接收到的map中的商品id及其对应的数量信息
        HashMap<Integer, Integer> proIdCount = new HashMap<>();
        int len = productIdAndCount.size();
        for (int i=0;i<len;i++){
            while (iterator.hasNext()){
                Map.Entry<String, String> next = iterator.next();
                String key = next.getKey();
                String value = next.getValue();
                proIdCount.put(Integer.parseInt(key),Integer.parseInt(value));
            }
        }

        // 返回的都是 ServerResponse，返回的又不止是一个 ServerResponse 类型的值，所以使用 List<ServerResponse> 集合进行输出
        ArrayList<ServerResponse> serverResponseArrayList = new ArrayList<>();
        // 获得收件地址
        ServerResponse serverResponseAddressList = placeAnOrderService.getByCustomerIdAddress(customerId);

        ServerResponse byCarProductList = placeAnOrderService.getByCarProductId(proIdCount);

        // 将查询到的数据添加到 集合中
        serverResponseArrayList.add(serverResponseAddressList);
        serverResponseArrayList.add(byCarProductList);

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("serverResponseArrayList",serverResponseArrayList);
        modelAndView.setViewName("order/place_an_order");



        String url = "/order/place_an_order/xiadanyemian?builder="+builder;
        //String url = "/order/place_an_order/xiadanyemain?customerId="+ customerId + "&productIdAndCount="+productIdAndCount;
        return url;
   }

    // 下单页面所需要的所有数据
    @GetMapping("/order/place_an_order/xiadanyemian")
    @ResponseBody
    public ModelAndView  placeAnOrderJSP(@RequestParam("builder") StringBuilder builder,Customer customer){
//        public String  placeAnOrderJSP(@RequestParam("customerId") Integer customerId,@RequestParam String productIdAndCount){


        // 商品id 与其对应的数量 key：value
        Map<Integer, Integer> map =  new HashMap<>();
        // 解析数据
        // key13-1qkey22-1qkey44-2qkey55-3q
        String s = builder.toString();
        System.out.println("sssssss======" + s);
        while (s.length() != 0){
            // key13-11qkey44-11qkey55-3q
            String str = s.substring(0,s.indexOf("q")+1);
            String key = str.substring(str.indexOf("y")+1,str.indexOf("-"));

            // 拿到的是 value 的值
            String value = str.substring(str.indexOf("-")+1,str.indexOf("q"));

            int q = s.indexOf("q");

            s = s.substring(q+1);
            map.put(Integer.parseInt(key),Integer.parseInt(value));
        }

        // 获得除了第一个收件地址的其他地址
        ServerResponse serverResponseAddressList = placeAnOrderService.getByCustomerIdAddress(customer.getCustId());

        // 返回数据库中的第一条收货地址
        ServerResponse byCustomerIdAddressFirst = placeAnOrderService.getByCustomerIdAddressFirst(customer.getCustId());

        // 返回订单总价格
        Double myOrderTotalPrice = placeAnOrderService.getMyOrderTotalPrice(map);
        ServerResponse byCarProductList = placeAnOrderService.getByCarProductId(map);

        ModelAndView modelAndView = new ModelAndView();
        // 返回除了第一个以外的其他收货地址信息
        modelAndView.addObject("serverResponseAddressList",serverResponseAddressList);
        // 返回的是第一条收货地址
        modelAndView.addObject("byCustomerIdAddressFirst",byCustomerIdAddressFirst);

        // 商品集合中还要包含商品的数量，所以还要建一个VO，用来装商品对象和其对应的商品id 的数量
        // 返回该订单中包含的商品集合
        modelAndView.addObject("byCarProductList",byCarProductList);

        // 返回订单的总价格
        modelAndView.addObject("myOrderTotalPrice",myOrderTotalPrice);

        modelAndView.setViewName("order/place_an_order");
//        return "redirect:/order/place_an_order.jsp";
//        return serverResponseArrayList;
        return modelAndView;
    }


}